package com.zat.mes.andrmes.dofun.main

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.BindMachineBean
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.main.adapter.BindMachineAdapter
import com.zat.mes.andrmes.dofun.main.vm.BindMachineModel
import com.zat.mes.andrmes.dofun.qualitytest.OnSiteActivity
import com.zat.mes.andrmes.dofun.work.onRequestPermissionsResult
import com.zat.mes.andrmes.dofun.work.showCameraWithPermissionCheck
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.activity_bind_machine.*
import kotlinx.android.synthetic.main.layout_head_clock.*
import kotlinx.android.synthetic.main.layout_title.*
import permissions.dispatcher.*
import java.util.*

/**
 * 绑定设备activity
 */
@RuntimePermissions
class BindMachineActivity : BaseActivity() {

    lateinit var bindModel: BindMachineModel
    var bindMachineAdapter:BindMachineAdapter?=null
    override fun init() {
        setContentView(R.layout.activity_bind_machine)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }

        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        val empId = loginResultBean.empid
        val empName = loginResultBean.empname
        tvNameBind.text = empName
        tVtitle.text = "绑定设备"
        GlideUtil.setHeader(this, loginResultBean?.img, ivHeadBind)
        tvCanlendarBind.text = DateUtil.formatDate(Date(), getString(R.string.head_date)) + DateUtil.getWeek(Date())
        bindMachineAdapter = BindMachineAdapter(R.layout.item_bindmachine_list,object :BindMachineAdapter.UnbindListener{
            override fun unBind(bindMachineBean: BindMachineBean) {
                showLoading()
                bindModel.delBind(bindMachineBean.bindingId)

            }

        });
        recyclerBind.layoutManager = LinearLayoutManager(baseContext,LinearLayoutManager.VERTICAL,false)
        recyclerBind.adapter = bindMachineAdapter

        bindModel = ViewModelProvider(this).get(BindMachineModel::class.java)
        bindModel.getBindData().observe(this, Observer {
            closeLoading()
            Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
            Handler().postDelayed(Runnable { requestList(empId) },500)

        })
        bindModel.getBindDataList().observe(this, Observer {
            closeLoading()
            bindMachineAdapter?.setNewData(it as MutableList<BindMachineBean>?)
            if (it != null && it?.size > 0) {
                setEmptyGone()
            } else {
                setEmptyVisible()
            }

        })
        bindModel.getDelBindData().observe(this, Observer {
            showToast(it)
            showLoading()
            requestList(empId)
        })

        llScanBind.setOnClickListener {
            showCameraWithPermissionCheck()
        }
        showLoading()
        requestList(empId)

    }

    private fun requestList(empId: Long) {
        bindModel.loadBindList(empId.toString());
    }

    /**
     * 请求去人员绑定
     */
    fun loadBindMachine(qrCode: String?) {
        showLoading()
        val loginResultBean: LoginResultBean? = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        loginResultBean?.let {
            bindModel.loadBind(loginResultBean?.empid, loginResultBean?.empEnName, qrCode);
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
            if (qrCode != null) {
                if (qrCode?.startsWith(CompanionType.STRING_QR_MAC)) {
                    //人员设备绑定
                    loadBindMachine(qrCode)
                }
            }

        }
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(
                Intent(this, QrScanActivity::class.java),
                CompanionCode.REQUESTCODE
            )
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }


}
